const crypto = require('crypto');

// 生成 RSA 密钥对
function generateKeyPair() {
    return new Promise((resolve, reject) => {
        crypto.generateKeyPair('rsa', {
            modulusLength: 2048,
        }, (err, publicKey, privateKey) => {
            if (err) {
                reject(err);
            } else {
                resolve({ publicKey, privateKey });
            }
        });
    });
}

// 加密数据
function encryptData(publicKey, data) {
    const iv = crypto.randomBytes(16); // 生成随机的初始化向量
    const cipher = crypto.createCipheriv('aes-256-cbc', publicKey, iv);
    let encrypted = cipher.update(data);
    encrypted = Buffer.concat([encrypted, cipher.final()]);
    return { iv, encrypted };
}

// 解密数据
function decryptData(privateKey, encryptedData) {
    const decipher = crypto.createDecipheriv('aes-256-cbc', privateKey, encryptedData.iv);
    let decrypted = decipher.update(encryptedData.encrypted);
    decrypted = Buffer.concat([decrypted, decipher.final()]);
    return decrypted.toString();
}

// 示例用法
(async function() {
    try {
        let { publicKey, privateKey } = await generateKeyPair();
        publicKey = 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC0WdtVr8Rp8AFJVCZAKx3wvrhlVcDQaFigJ4SyxrvnGdOnxMdxneBgxTl2pr2kac7sU7WHj4nqaHeMOFkS9UrA+xFm7OQSodE3o8vWxBe2B+t1J9XixFgnLWL8WdNMhVsMO1qdwgfwEGbLQqmXzoIWUMxfE2O1JKG3bqs02AyvIQIDAQAB'
        const publicObject = crypto.publicKeyInPemFormatToPublicKey(publicKey);
        const data = 'Hello, RSA!';
        const encryptedData = encryptData(publicObject, data);
        console.log('Encrypted data:', encryptedData);
        const decryptedData = decryptData(privateKey, encryptedData);
        console.log('Decrypted data:', decryptedData);
    } catch (err) {
        console.error('Error:', err);
    }
})();
